<template>
  <div ref="chartRef" :style="{ width: '100%', height: '100%' }"></div>
</template>

<script lang="ts">
import { Card } from "ant-design-vue";
import { defineComponent, reactive, ref, watch } from "vue";
import * as echarts from "echarts";
import { ChartsParams, getScenceLatencyApi } from "@/api/scence";
import eventBus from "@/utils/eventBus";
import _ from "lodash";
import { useBusinessRequestModuleStore } from "@/store/businessRequests";
import { chartKeyOptions, formatQPSlegend } from "./dataJson";
export default defineComponent({
  components: {
    Card,
  },
  props: {
    tabInfo: {
      type: Object,
    },
  },
  setup(props) {
    const chartRef = ref<any>();
    const store = useBusinessRequestModuleStore();
    const selectedRequset = ref(store.getBusinessRequest);

    const formatBigTime = (value: number) => {
      if (value >= 1e9) {
        return (value / 1e9).toFixed(2) + "G";
      } else if (value >= 1e6) {
        return (value / 1e6).toFixed(2) + "M";
      } else if (value >= 1e3) {
        return (value / 1e3).toFixed(2) + "k";
      } else {
        return value.toString();
      }
    };

    const chartOptions = reactive({
      title: {
        // text: "",
      },
      // grid: { containLabel: true },
      grid: {
        left: "15%",
      },
      legend: {
        data: props.tabInfo?.legend,
      },
      color: chartKeyOptions[props.tabInfo?.key].color,
      xAxis: {
        boundaryGap: false,
        type: "category",
        data: [],
        axisLabel: {
          interval: function (index, value) {
            const timeComponents = value.split(":");
            const minutes = parseInt(timeComponents[1]);
            // 设置标签显示条件，例如每隔5分钟显示一个标签
            return minutes % 5 === 0 ? true : false;
          },
        },
      },
      yAxis: {
        name: props.tabInfo?.unit,
        axisLabel: {
          formatter: (value: number) => formatBigTime(value),
        },
      },
      series: [],
      tooltip: {
        trigger: "axis",
        // formatter:
        //   props.tabInfo?.type === "multiple"
        //     ? function (params: any) {
        //         var htmlStr = "";
        //         for (var i = 0; i < params.length; i++) {
        //           var param = params[i];
        //           var xName = param.name;
        //           var seriesName = param.seriesName;
        //           var value = param.value;
        //           var color = param.color;
        //           if (i === 0) {
        //             htmlStr += xName + "<br/>";
        //           }
        //           htmlStr +=
        //             '<div><span style="margin-right:5px;display:inline-block;width:10px;height:10px;border-radius:5px;background-color:' +
        //             color +
        //             ';"></span>' +
        //             seriesName +
        //             `：<span style="font-weight:bolder">` +
        //             formatBigTime(value) +
        //             "</span></div>";
        //         }
        //         return htmlStr;
        //       }
        //     : null,
      },
    });

    const xAxisData = ref<string[]>([]);

    const now = ref<Date>(new Date());
    const POLLING_INTERVAL = 30000;
    const pollingInterval = ref<any>(null);
    const halfAnHourAgo = ref<Date>(new Date());
    // 调整为UTC-8时区

    const formatDateTime = (date: any) => {
      date = new Date(date.getTime() - 8 * 60 * 60 * 1000);
      let year = date.getFullYear();
      let month = (date.getMonth() + 1).toString().padStart(2, "0");
      let day = date.getDate().toString().padStart(2, "0");
      let hours = date.getHours().toString().padStart(2, "0");
      let minutes = date.getMinutes().toString().padStart(2, "0");
      let result = `${year}-${month}-${day} ${hours}${minutes}`;
      // if (!props.tabInfo?.isMinutePrecision) {
      result += `00`;
      // }
      return result;
    };
    const formatTimestampToHHMM = (timestamp: number) => {
      const date = new Date(timestamp);
      // console.log(timestamp);
      // console.log(date);
      var hours = date.getHours().toString().padStart(2, "0");
      var minutes = date.getMinutes().toString().padStart(2, "0");
      var formattedTime = hours + ":" + minutes;
      return formattedTime;
    };

    const initEcharts = () => {
      chartOptions.xAxis.data = xAxisData.value;
      let chart = echarts.getInstanceByDom(chartRef.value);
      if (!chart) {
        chart = echarts.init(chartRef.value);
      }
      chart.setOption(chartOptions, false);
    };
    async function pollingFunction() {
      try {
        await fetchData();
      } catch (error) {
        console.log(error);
      }
    }
    async function fetchData() {
      try {
        now.value = new Date(Date.now() - 60 * 1000);
        halfAnHourAgo.value = new Date(now.value.getTime() - 30 * 60 * 1000);
        const params: ChartsParams = {
          serviceName: selectedRequset.value.serviceName,
          endpointName: selectedRequset.value.endpointName,
          start: formatDateTime(halfAnHourAgo.value),
          end: formatDateTime(now.value),
        };
        if (props.tabInfo?.percent) {
          params.percent = props.tabInfo.percent;
        }
        const res = await props.tabInfo?.api(params);
        if (res.code === "0") {
          chartOptions.series = [];
          _.forEach(res.data, (lineData: object, key: string) => {
            const sortedLatenciesArray = _.orderBy(
              _.toPairs(lineData),
              ([timestamp]) => parseInt(timestamp),
              "asc"
            );
            const sortedTimestampsArray = sortedLatenciesArray.map(
              ([timestamp]) => {
                const parsedTimestamp = parseInt(timestamp);
                return formatTimestampToHHMM(parsedTimestamp);
              }
            );
            const sortedValuesArray = sortedLatenciesArray.map(([, value]) =>{
              return props.tabInfo?.key !== "throughputs"
                ? (value / 1000000).toFixed(2)
                : value.toFixed(2)}
            );
            xAxisData.value = sortedTimestampsArray;
            const yAxisItem = {
              name: chartKeyOptions[key]
                ? chartKeyOptions[key].legend
                : formatQPSlegend(key),
              type: "line",
              showSymbol: false,
              data: sortedValuesArray,
            };
            chartOptions.series.push(yAxisItem);
          });
          // chartOptions.series[0].data = _.values(res.data)[0];
          initEcharts();
        }
      } catch (error) {
        throw error;
      }
    }
    watch(
      () => store.getBusinessRequest,
      (newValue, oldValue) => {
        selectedRequset.value = newValue;
        initPollingInterval();
      }
    );
    const initPollingInterval = () => {
      if (pollingInterval.value) {
        clearInterval(pollingInterval.value);
      }
      pollingFunction();
      pollingInterval.value = setInterval(pollingFunction, POLLING_INTERVAL);
    };
    initPollingInterval();

    return {
      chartOptions,
      halfAnHourAgo,
      chartRef,
      selectedRequset,
      pollingInterval,
    };
  },
  beforeUnmount() {
    clearInterval(this.pollingInterval);
  },
});
</script>

<style lang="less" scoped>
.scence-card :deep(.ant-card-body) {
  height: 100%;
  // padding: 10px;
}
.scence-card {
  display: flex;
  flex-direction: column;
}
</style>